package com.xyzwps.ewa.modules.auth

import com.xyzwps.ewa.common.ServerException
import com.xyzwps.ewa.modules.auth.password.PasswordRepository
import com.xyzwps.ewa.modules.auth.password.ThePasswordEncryptor
import com.xyzwps.ewa.modules.user.User
import com.xyzwps.ewa.modules.user.UserRepository
import io.ktor.http.*
import org.jetbrains.exposed.sql.transactions.transaction

object UsernamePasswordLoginService {
    fun login(username: String, password: String): User = transaction {
        val user = UserRepository.findByUsername(username) ?: throw loginFailed()
        val passwordInfo = PasswordRepository.read(user.id) ?: throw loginFailed()
        if (ThePasswordEncryptor.verify(password, passwordInfo.encrypted)) {
            user
        } else {
            throw loginFailed()
        }
    }

    private fun loginFailed() = ServerException(
        "Username or password invalid", HttpStatusCode.BadRequest
    )
}